__author__ = 'vladbranzei'

import pymongo
from pymongo.errors import DuplicateKeyError
from cherrypy import HTTPError
from configs import configs as conf

class Entry(object):
    id=leaderboard_id=owner=score=rank=display_name=custom_fields=None

    def __init__(self, i_id, i_game, i_name, i_type, i_order, i_creation_time):
        self.id = i_id
        self.game = i_game
        self.name = i_name
        self.order = i_order
        self.creation_time = i_creation_time
        self.type = i_type

class EntriesMapper(object):
    def __init__(self):
        self.foundEntry = None
        self.client = conf.client

    def add_entry(self, i_leaderboard_id, i_owner, i_score, i_display_name, i_custom_fields):

        update = {}
        update['leaderboard_id'] = i_leaderboard_id
        update['owner'] = i_owner
        update['score'] = i_score
        update['display_name'] = i_display_name
        update['custom'] = i_custom_fields

        try:
            result = self.client.ulise.entries.update({'leaderboard_id':i_leaderboard_id, "owner":i_owner}, update, True)

            if result['ok']:
                return True
            else:
                raise HTTPError(500)

        except DuplicateKeyError as e:
            raise e
        except HTTPError as e:
            raise e
        except Exception as e:
            raise HTTPError(503)

    def check(self, i_leaderboard_id, i_owner):
        query = {}
        query['leaderboard_id'] = i_leaderboard_id
        query['i_owner'] = i_owner

        try:
            cursor = self.client.ulise.entries.find(query)
            count = cursor.count()
            if count == 1:
                self.foundEntry = cursor[0]
                return True
            else:
                return False
        except Exception as e:
            raise HTTPError(503)

    def _get_leaderboard_entries(self, i_leaderboard_id, i_order, i_offset, i_limit):
        query = {}
        query['leaderboard_id'] = i_leaderboard_id

        try:
            order = None
            if i_order == "asc":
                order = pymongo.ASCENDING
            else:
                order = pymongo.DESCENDING

            cursor = self.client.ulise.entries.find(query).skip(i_offset).limit(i_limit).sort([('score', order)])
            count = cursor.count()
            result = {}
            result["count"] = count
            entries = []
            for entry in cursor:
                ey = {"leaderboard_id":entry['leaderboard_id'],"owner":entry['owner'],"custom":entry['custom'], "score":entry['score'], "display_name":entry['display_name']}
                entries.append(ey)
            result['entries'] = entries

            return result
        except Exception as e:
            raise HTTPError(503)

